package com.heima.comment.seivice.impl;

import com.heima.article.feign.ApArticleFeign;
import com.heima.comment.seivice.ApCommentService;
import com.heima.common.dtos.Result;
import com.heima.common.exception.AppHttpCodeEnum;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.feign.ApUserFeign;
import com.heima.utils.common.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;

@Service
@Transactional
public class ApCommentServiceImpl implements ApCommentService {
    @Autowired
    private ApUserFeign apUserFeign;
    @Autowired
    private ApArticleFeign apArticleFeign;
    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 发表评论
     */
    @Override
    public Result saveComment(CommentSaveDto dto) {
        //判断是否登录
        ApUser apUser = (ApUser) ThreadLocalUtils.get();
        if(apUser==null){
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }
        try {
            apUser = apUserFeign.findOne(apUser.getId()).getData();
            if(dto.getContent().length()>140){
                throw new LeadNewsException(500,"评论内容不大于140个字");
            }
            //保存评论
            ApComment apComment = new ApComment();
            apComment.setAuthorId(apUser.getId());
            apComment.setAuthorName(apUser.getName());
            apComment.setImage(apUser.getImage());
            apComment.setEntryId(dto.getArticleId());//关联文章
            apComment.setFlag(0);
            apComment.setContent(dto.getContent());
            apComment.setLikes(0);
            apComment.setReply(0);
            apComment.setType(0);
            apComment.setCreatedTime(new Date());

            //查询文章信息
            ApArticle apArticle = apArticleFeign.findById(dto.getArticleId());
            if(apArticle!=null) {
                apComment.setChannelId(apArticle.getChannelId());
            }
            mongoTemplate.insert(apComment);
            return Result.ok();
        } catch (LeadNewsException e) {
            e.printStackTrace();
            throw new LeadNewsException(AppHttpCodeEnum.SERVER_ERROR);
        }


    }
    /**
     * 评论点赞
     */
    @Override
    public Result<Map<String, Integer>> likeComment(CommentLikeDto dto) {

//判断用户登录
        ApUser apUser = (ApUser)ThreadLocalUtils.get();
        if(apUser==null){
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }
        try {
            //查询该用户的评论点赞记录
            Query query = Query.query(Criteria.where("authorId").is(apUser.getId()).and("commentId").is(dto.getCommentId()));
            long count = mongoTemplate.count(query, ApCommentLike.class);
            if (count == 0 && dto.getOperation().equals(0)){
                ApCommentLike apCommentLike = new ApCommentLike();
                apCommentLike.setAuthorId(apUser.getId());
                apCommentLike.setCommentId(dto.getCommentId());
                mongoTemplate.save(apCommentLike);
            }else {
                //如果有记录，删除点赞记录，评论的点赞数-1
                //删除评论点赞记录
                mongoTemplate.remove(query,ApCommentLike.class);
            }
            Query commentQuery = Query.query(Criteria.where("_id").is(dto.getCommentId()));
            Update update = new Update();

            if (dto.getOperation().equals(0)){
                update.inc("like");
            }else{
                update.inc("like",-1);
            }
            mongoTemplate.updateMulti(commentQuery,update,ApComment.class);

            ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
            Map<String, Integer> result = new HashMap<>();
            result.put("likes",apComment.getLikes());

            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            throw new LeadNewsException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
